//
//  AddPhoneContactVC.m
//  jinwang
//
//  Created by jzb on 2018/3/26.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "AddPhoneContactVC.h"
#import "AddPhoneContactCell.h"
#import <Contacts/Contacts.h>
#import <AddressBook/AddressBookDefines.h>
#import <AddressBook/ABRecord.h>
#import "AddPhoneContactModel.h"

@interface AddPhoneContactVC ()
{
    NSMutableDictionary *_contactsDic;
}

@property (nonatomic,strong) AddPhoneContactCell *cell;
@property (nonatomic,strong) NSMutableArray *ListmodelArr;

@end

@implementation AddPhoneContactVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"手机联系人";
    _contactsDic = [NSMutableDictionary new];
    [self setUpTableView];
    [self requestContactAuthorAfterSystemVersion9];
}
//配置tableView
-(void)setUpTableView{
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    //注册cell
    self.tableView.estimatedRowHeight = UITableViewAutomaticDimension;
    [self registerCellWithCellClassArray:@[NSStringFromClass([AddPhoneContactCell class])]];
    
}
#pragma mark -UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _ListmodelArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.cell = [tableView dequeueReusableCellWithIdentifier:[AddPhoneContactCell getCellReuseIdentifier]];
    self.cell.contentView.backgroundColor = [UIColor clearColor];
    
    [self.cell.AddBtn addTarget:self action:@selector(cellButtonOnclikc:) forControlEvents:UIControlEventTouchUpInside];
    
    self.cell.AddBtn.tag = 1000+indexPath.row;

    self.cell.model = _ListmodelArr[indexPath.row];
    
    return self.cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 71;
}
- (void)cellButtonOnclikc:(UIButton *)sender{
    
    AddPhoneContactModel *model = _ListmodelArr[sender.tag - 1000];
    
    [self makeUrl_batchAddFriendsWithUser_id:[NSString stringWithFormat:@"%@",model.user_id]];
}

//请求通讯录权限
#pragma mark 请求通讯录权限
- (void)requestContactAuthorAfterSystemVersion9{
    
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
            if (error) {
                NSLog(@"授权失败");
            }else {
                NSLog(@"成功授权");
            }
        }];
    }
    else if(status == CNAuthorizationStatusRestricted)
    {
        NSLog(@"用户拒绝");
        [self showAlertViewAboutNotAuthorAccessContact];
    }
    else if (status == CNAuthorizationStatusDenied)
    {
        NSLog(@"用户拒绝");
        [self showAlertViewAboutNotAuthorAccessContact];
    }
    else if (status == CNAuthorizationStatusAuthorized)//已经授权
    {
        //有通讯录权限-- 进行下一步操作
        [self openContact];
    }
    
}

//有通讯录权限-- 进行下一步操作
- (void)openContact{
    // 获取指定的字段,并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

        //拼接姓名
        NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        
        NSArray *phoneNumbers = contact.phoneNumbers;
        
        for (CNLabeledValue *labelValue in phoneNumbers) {
            //遍历一个人名下的多个电话号码
//            NSString *label = labelValue.label;
//            NSString *    phoneNumber = labelValue.value;
            CNPhoneNumber *phoneNumber = labelValue.value;
            
            NSString * string = phoneNumber.stringValue ;
            
            //去掉电话中的特殊字符
            string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"  " withString:@""];
            string = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
            
//            NSLog(@"姓名=%@, 电话号码是=%@", nameStr, string);
            [_contactsDic setObject:nameStr forKey:string];
            
        }
        //    *stop = YES; // 停止循环，相当于break；
    }];
    [self makeUrl_batchContacts];
}
//提示没有通讯录权限
- (void)showAlertViewAboutNotAuthorAccessContact{
    
    UIAlertController *alertController = [UIAlertController
                                          alertControllerWithTitle:@"请授权通讯录权限"
                                          message:@"请在iPhone的\"设置-隐私-通讯录\"选项中,允许花解解访问你的通讯录"
                                          preferredStyle: UIAlertControllerStyleAlert];
    
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:OKAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark -网络请求
//上传手机联系人
-(void)makeUrl_batchContacts{
    
    [[DDNetworkManagerDate makeUrl_batchAddContacts_with_token:k_user_token contacts:[self dictionaryToJson:_contactsDic]] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"----->>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
         
            NSArray *data = [responseObject objectForKey:kRequsetDataKey];
            //转模型
            NSMutableArray *arr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                AddPhoneContactModel *model = [AddPhoneContactModel yy_modelWithDictionary:obj];
                [arr addObject:model];
            }];
            self.ListmodelArr = arr.mutableCopy;
            
        }
        [self.tableView reloadData];
    } failure:^(id errorObject) {
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//添加好友
-(void)makeUrl_batchAddFriendsWithUser_id:(NSString *)user_id{
    
    [[DDNetworkManagerDate makeUrl_batchAddFriends_with_token:k_user_token user_id:user_id] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"----->>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
        }
    } failure:^(id errorObject) {
        [self showBottomMessag:@"网络请求失败"];
    }];
}




- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
